package com.essearch.controller;

import com.essearch.document.ProductDocument;
import com.essearch.model.Req;
import com.essearch.page.Page;
import com.essearch.service.ElasticsearchService;
import com.essearch.service.EsSearchService;
import com.essearch.util.JsonUtil;
import org.elasticsearch.client.transport.TransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * elasticsearch 搜索..
 *   增删改查__批量插入、分页查询。分词搜索-keyword
 */
@RestController
public class EsSearchController {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private EsSearchService esSearchService;

    @Resource // TransportClient 客户端。
    private ElasticsearchService elasticsearchService;

    @Resource
    private TransportClient transportClient;


    // insertById
    @RequestMapping("insert")
    public String insert() throws IOException {
        for (int i = 0; i < 5; i++) {
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("id",i);
            dataMap.put("productName", "电脑"+i);
            dataMap.put("productDesc", "这是一个电脑"+i);
            dataMap.put("createTime",new Date());
            elasticsearchService.insertById("index_1", "index_1", i+"", dataMap);
        }
        return "insert data sucess...";
    }
    // update
    @RequestMapping("update")
    public String update() throws IOException {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("productName", "大头娃娃");
        dataMap.put("productDesc", "这是一个可爱的鼠标");
        elasticsearchService.update("es_order3", "es_order3", "1", dataMap);
        return "update data sucess...";
    }
    /**
     * 新增 / 修改索引
     * @return
     * @RequestBody ProductDocument productDocument
     */
    @RequestMapping("save")
    public String add() {
        ProductDocument product=new ProductDocument();
        product.setId("2");
        product.setProductName("耳机");
        product.setProductDesc("这是一个蓝牙耳机");
        product.setCreateTime(new Date());
        product.setUpdateTime(new Date());
        esSearchService.save(product);
        return "success";
    }
    /**
     * 根据ID获取
     * @return
     */
    @RequestMapping("get/{id}")
    public ProductDocument getById(@PathVariable String id){
        return esSearchService.getById(id);
    }

    /**
     * 根据获取全部
     * @return
     */
    @RequestMapping("getAll")
    public List<ProductDocument> getAll() {
        System.out.println(transportClient.listedNodes());
        return esSearchService.getAll();
    }

    @RequestMapping("getPage")
    public String getClient(String indexName,int page) {
        return JsonUtil.toJson(elasticsearchService.queryAllByIndex(indexName, page));
    }

    @RequestMapping("getReq")
    public String getReq(Req req) {
        return JsonUtil.toJson(elasticsearchService.queryAllByReq("es_order",req));
    }

    /**
     * 搜索
     * @param keyword
     * @return
     */
    @RequestMapping("query/{keyword}")
    public List<ProductDocument> query(@PathVariable String keyword){
        return esSearchService.query(keyword,ProductDocument.class);
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8080/query_hit?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit")
    public List<Map<String,Object>> queryHit(@RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){
        String[] fieldNames = {};
        if(fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return esSearchService.queryHit(keyword,indexName,fieldNames);
    }

    /**
     * 搜索，命中关键字高亮
     * http://localhost:8080/query_hit_page?keyword=无印良品荣耀&indexName=orders&fields=productName,productDesc&pageNo=1&pageSize=1
     * @param pageNo    当前页
     * @param pageSize  每页显示的数据条数
     * @param keyword   关键字
     * @param indexName 索引库名称
     * @param fields    搜索字段名称，多个以“，”分割
     * @return
     */
    @RequestMapping("query_hit_page")
    public Page<Map<String,Object>> queryHitByPage(@RequestParam int pageNo, @RequestParam int pageSize
                                                    , @RequestParam String keyword, @RequestParam String indexName, @RequestParam String fields){
        String[] fieldNames = {};
        if(fields.contains(",")) fieldNames = fields.split(",");
        else fieldNames[0] = fields;
        return esSearchService.queryHitByPage(pageNo,pageSize,keyword,indexName,fieldNames);
    }
}
